<template>
    <div class="upload-page">
        <div class="title">上传文件到阿里云 OSS</div>

        <form @submit.prevent="uploadFile" class="upload-form">
            <input type="file" @change="handleFileChange" class="file-input" />
            <button type="submit" class="upload-btn" :disabled="!selectedFile">上传文件</button>
        </form>

        <div v-if="uploadStatus" class="upload-status">
            <h3 class="status-title">上传结果：</h3>
            <p v-if="uploadStatus === 'success'" class="success-message">
                文件上传成功！<br />
                <a :href="fileUrl" target="_blank" class="file-link">点击查看文件</a>
            </p>
            <p v-else class="error-message">文件上传失败，请重试。</p>
        </div>

        <div v-if="datalist" class="data-info">
            <div v-if="datalist == null || Object.keys(datalist).length === 0">
                <h3 class="loading">审核中，请稍候……</h3>
            </div>
            <div v-else class="info">
                <div class="info-item"><span class="info-label">姓名：</span>{{ datalist.name }}</div>
                <div class="info-item"><span class="info-label">性别：</span>{{ datalist.sex }}</div>
                <div class="info-item"><span class="info-label">出生日期：</span>{{ datalist.birth }}</div>
                <div class="info-item"><span class="info-label">民族：</span>{{ datalist.mz }}</div>
                <div class="info-item"><span class="info-label">地址：</span>{{ datalist.address }}</div>
                <div class="info-item"><span class="info-label">身份证：</span>{{ datalist.code }}</div>
            </div>
        </div>

        <el-button class="face-btn" @click="face">人脸识别</el-button>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const router = useRouter();

// 响应式变量
const selectedFile = ref(null); // 存储用户选择的文件
const uploadStatus = ref(''); // 上传状态 ("success" 或 "error")
const fileUrl = ref(''); // 上传成功后返回的文件 URL

// 获取 CSRF Token 的函数
function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(";").shift();
}
const csrfToken = getCookie('csrftoken');

// 处理文件选择
const handleFileChange = (event) => {
    selectedFile.value = event.target.files[0]; // 获取选中的文件
};
const datalist = ref([]);

// 上传文件到后端
const uploadFile = async () => {
    if (!selectedFile.value) {
        alert('请选择一个文件！');
        return;
    }

    // 构造 FormData 对象
    const formData = new FormData();
    formData.append('file', selectedFile.value);

    try {
        // 发送 POST 请求到后端
        const response = await axios.post('http://127.0.0.1:8000/app/upload/', formData, {
            headers: {
                'X-CSRFToken': csrfToken, // 添加 CSRF Token
                'Content-Type': 'multipart/form-data',
            },
        });

        // 处理响应数据
        if (response.data.status === 'success') {
            uploadStatus.value = 'success';
            fileUrl.value = response.data.file_url; // 后端返回的文件 URL
            localStorage.setItem('file_url', fileUrl.value); // 存储文件 URL 到本地存储
        } else {
            uploadStatus.value = 'error';
        }

        axios.get('http://127.0.0.1:8000/app/idcard/', { params: { 'url': fileUrl.value } })
            .then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.msg);
                }

                const t = setInterval(() => {
                    axios.get('http://127.0.0.1:8000/app/userinfo/', { params: { 'url': fileUrl.value } }).then(res => {
                        if (res.data.code == 200) {
                            datalist.value = res.data.msg;
                            clearInterval(t);
                        }
                    });
                }, 1000);
            });
    } catch (error) {
        console.error('文件上传失败:', error);
        uploadStatus.value = 'error';
    }

};

const face = () => {
    router.push('/face');
};

</script>

<style scoped>
.upload-page {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #f7f8fa;
    padding: 20px;
    transform: translate(-50%);
    left: 50%;
    position: relative;
    width: 400px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    text-align: center;
}

.title {
    font-size: 24px;
    font-weight: bold;
    color: #333;
    margin-bottom: 20px;
}

.upload-form {
    width: 100%;
    margin-bottom: 20px;
}

.file-input {
    width: 100%;
    padding: 10px;
    margin-bottom: 10px;
    font-size: 16px;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.upload-btn {
    width: 100%;
    padding: 10px;
    font-size: 16px;
    font-weight: bold;
    color: #fff;
    background: linear-gradient(45deg, #4caf50, #66bb6a);
    border: none;
    border-radius: 25px;
    cursor: pointer;
}

.upload-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
}

.upload-status {
    margin-top: 20px;
    text-align: center;
}

.status-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
}

.success-message {
    color: #4caf50;
}

.error-message {
    color: red;
}

.file-link {
    color: #007bff;
    text-decoration: underline;
}

.file-link:hover {
    color: #0056b3;
}

.data-info {
    margin-top: 20px;
    width: 100%;
    text-align: left;
    padding: 10px;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.loading {
    font-size: 16px;
    font-style: italic;
    color: #666;
}

.info {
    font-size: 16px;
}

.info-item {
    margin: 5px 0;
    display: flex;
    justify-content: space-between;
}

.info-label {
    font-weight: bold;
    color: #333;
}

.face-btn {
    margin-top: 20px;
    padding: 10px 20px;
    font-size: 16px;
    font-weight: bold;
    color: #fff;
    background: linear-gradient(45deg, #2196f3, #42a5f5);
    border: none;
    border-radius: 25px;
    cursor: pointer;
}

.face-btn:hover {
    background: linear-gradient(45deg, #1e88e5, #2196f3);
}
</style>
